<template>
    <view>
		<template v-if="loading">
			<u-loading-page :loading="loading"></u-loading-page>
		</template>
		
		<template v-else>
			<u-popup :show="showLoginPopup" mode="bottom" :round=20 @close="closePopup" :closeOnClickOverlay="false">
				<view class="cotainer">
			        <u-image src="/static/icons/school_login_logo.jpg" width="130px" height="130px" 
			            custom-style="margin-top: 30px; margin-bottom: 20px;" />
			        <u-input v-model="userId" placeholder="学号/账号" 
			            custom-style="margin-bottom: 5px;"
			            placeholder-style="color: #1e74ff; text-align: center" />
			        <u-input v-model="password" password placeholder="密码" 
			            placeholder-style="color: #1e74ff; text-align: center" />
			        <u-button type="primary" @click="saveInfo"
						custom-style="margin-top: 20px; margin-bottom: 30%; background-color: #1e74ff;">
						登录
					</u-button>
			    </view>
			</u-popup>
			
			<ly-curriculumtable  :weekTableState="true" :weekTableNumber="weekNumbers" 
			 :controlWeek="controlWeek" :timetableType="timetableType" 
			 :timetables="timetables" :startdDate="startdDate" :weekButton="weekButton" 
			 @nextWeekClick="nextWeekClick" @lastWeekClick="lastWeekClick" 
			 @courseClick="courseClick" @weekSelectClick="weekSelectClick" 
			 @weekOpenClick="weekOpenClick">
			
			 </ly-curriculumtable> 
			 <!-- 课程详情 -->
			 <u-modal class="modal" :show="showMyModal"  title="课程详情" 
			                :closeOnClickOverlay="true" 
			                :showConfirmButton="false" @close="closeModal">
			    <view class="slot-content">
			        <u-cell-group>
			            <u-cell
			                v-for="(item,index) in modalItem" :key="index"
			                :title="item"
			                :icon="modalIcon[index]"
			                        :iconStyle="{color: colorList()[index+1]}"
			                size="large"
			            ></u-cell>
			        </u-cell-group>
			    </view>
			 </u-modal>
		</template>
    </view>
</template>
<script>
	export default {
		data() {
			return {

				weekNumbers:20,//一共显示几周
				controlWeek: undefined,//显示的第几周
				weekButton:true,//开启上一周下一周按钮
				startdDate: undefined, //开始时间  默认为当前时间
				timetables: undefined,
				timetableType:[ 
				   { index: '1', name: '08:10\n08:55' },
				   { index: '2', name: '09:05\n09:50' },
				   { index: '3', name: '10:20\n11:05' },
				   { index: '4', name: '11:15\n12:00' },
				   { index: '5', name: '13:30\n14:15' },
				   { index: '6', name: '14:25\n15:10' },
				   { index: '7', name: '15:40\n16:25' },
				   { index: '8', name: '16:35\n17:20' },
				   { index: '9', name: '18:30\n19:15' },
				   { index: '10', name: '19:25\n20:10'},
				   { index: '11', name: '20:50\n21:30'},
				   { index: '12', name: '21:40\n22:20'}],
				//弹窗属性
				showMyModal: false,//课程详情弹窗
				modalIcon: ['calendar','home','server-man','clock'],//图标
				modalItem: [],//依次是课程名、教室、教师、上课时间--为了适配渲染
				
				showLoginPopup: false,
				userId: "",
				password: "",
				
				loading: true,
			}

		},
		methods:{
			clearTimetable(){
				this.timetables = new Array(7)
				for (let i = 0; i < 7; i++) {
					this.timetables[i] = new Array(this.timetableType.length).fill('')
				}
			},
			getCurrentWeek(){
				return new Promise((resolve, reject) => {
					uni.request({
						url: getApp().globalData.zfapi_url + "/term_start_at",
						header: {
							"Access-Control-Allow-Origin": getApp().globalData.zfapi_url
						},
						method: "GET",
						success: (res) => {
							if ("msg" in res.data) {
								resolve(1)
							}
							let now = new Date()
							let day = res.data.term_start[0].day
							let month = res.data.term_start[0].month
							let termStart = new Date()
							termStart.setMonth(month-1, day)
							if (termStart > now) {
								termStart.setFullYear(termStart.getFullYear() - 1)
							}
							this.startdDate = termStart.toLocaleDateString()
							let nowDiff = now.getDay() == 0 ? 6 : now.getDay() - 1
							let termStartDiff = termStart.getDay() == 0 ? 6 : termStart.getDay() - 1
							now.setDate(now.getDate() - nowDiff)
							termStart.setDate(termStart.getDate() - termStartDiff)
							resolve(parseInt(Math.ceil((now - termStart) / 6.048e8) + 1))
						},
						fail: () => {
							resolve(1)
						}
					})
				})
			},
			loadTimetable(userId, password, forceRefresh) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: getApp().globalData.zfapi_url + "/tb",
						header: {
							"Content-Type": "application/json",
							"Access-Control-Allow-Origin": getApp().globalData.zfapi_url
						},
						method: "POST",
						data: {
							userid: userId,
							password: password,
							force_refresh: forceRefresh
						},
						success: (res) => {
							console.log(res.data)
							if ("msg" in res.data) {
								resolve(false)
							}
							this.courses = res.data.normalCourse
							resolve(true)
						},
						fail: (err) => {
							console.log(err)
							reject(err)
						}
					})
				})
			},
			saveInfo(){
				uni.showLoading({
					title: "登录中"
				})
				this.loadTimetable(this.userId, this.password, true).then(success => {
					if (!success) {
						uni.hideLoading()
						uni.showToast({
							title: "登录失败，请检查账号/密码",
							icon: "none"
						})
						return;
					}
					uni.setStorage({
						key: "schoolUserId",
						data: this.userId
					})
					uni.setStorage({
						key: "schoolPassword",
						data: this.password
					})
					this.showLoginPopup = false
					this.getCurrentWeek().then(weekNumber => {
						this.controlWeek = weekNumber
						this.refresh(this.controlWeek, true)
						uni.hideLoading()
					})
				})
			},
			refresh(weekNumber, forceRefresh) {
				if (this.courses == undefined || this.courses.length == 0 || forceRefresh) {
					let flag = true
					this.loadTimetable(this.userId, this.password, forceRefresh).then(res => flag = res)
					if (!flag) {
						return
					}
				}
				let hitCourses = []
				this.courseMap = {}
				for (let course of this.courses) {
					if (course.courseWeek.includes(weekNumber)) {
						hitCourses.push(course)
						this.courseMap[course.courseTitle] = course
					}
				}
				this.clearTimetable()
				for (let hitCourse of hitCourses) {
					let courseSection = hitCourse.courseSection
					let weekDay = hitCourse.weekday
					for (let section of courseSection) {
						this.timetables[weekDay - 1][section - 1] = hitCourse.courseTitle
					}
				}
			},
			courseClick(re){
				if(re.name) {
					this.modalItem[0]="课程: " + re.name;
					this.modalItem[1]="教室: " + this.courseMap[re.name].courseRoom
					this.modalItem[2]="教师: " + this.courseMap[re.name].teacher
					let startTime = this.timetableType[re.index-1].name.split('\n')[0]
					let endTime = this.timetableType[re.index+re.length-2].name.split('\n')[1]
					this.modalItem[3]="时间: " + startTime + "-" + endTime;
					this.showMyModal=true;
				}
			},
			nextWeekClick(e){
				this.controlWeek = e
				this.refresh(e, false)
			},
			lastWeekClick(e){
				if (e > this.weekNumbers) {
					return
				}
				this.controlWeek = e
				this.refresh(e, false)
			},
			weekOpenClick(){
				console.log("点击了第几周")
			},
			weekSelectClick(e){
				this.refresh(e, false)
			},
			//关闭弹窗
			closeModal(){
				this.showMyModal=this.showMyModal==true?false:true;
			},
			closePopup(){
				this.showLoginPopup = false
			},
			//返回颜色
			colorList() {
				return [
					"#ffffff", //0
					"#ffaa00", //1
					"#33CC99",
					"#ff5500", //3
					"#789262", //4
					"#66CCCC", //5
					"#9999FF", //6
				]
			},
		},
		options:{styleIsolation: 'shared'},
		onLoad() {
			this.clearTimetable()
			try {
				this.userId = uni.getStorageSync('schoolUserId')
				this.password = uni.getStorageSync('schoolPassword')
			} catch (ignore) {
				
			}
			this.loading = true
		},
		mounted() {
			this.loadTimetable(this.userId, this.password, false).then(
				(res) => {
					this.showLoginPopup = !res
					if (!this.showLoginPopup) {
						this.getCurrentWeek().then(weekNumber => {
							this.controlWeek = weekNumber
							this.refresh(this.controlWeek, false)
							this.loading = false
						})
					} else {
						uni.showToast({
							title: '获取课表失败',
							icon: 'error'
						})
						this.loading = false
					}
				}, 
				(reason) => {
					uni.showToast({
						title: '获取课表失败',
						icon: 'error'
					})
					this.showLoginPopup = true
					this.loading = false
				}
			)
		}
	}
</script>

<style lang="scss" scoped>
    .cotainer {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
		
		::v-deep .u-input {
			width: 60%!important;
			background-color: gainsboro!important;
			border-radius: 12px!important;
			min-height: 50px!important;
		}
		
		::v-deep .u-button {
			width: 20%!important;
			border-radius: 12px!important;
			min-height: 60px!important;
			font-size: 17px!important;
			font-weight: bolder!important;
		}
    }
</style>